<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/6/22
 * Time: 9:16
 */

namespace App\Http\Controllers\Finance;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Model\ProjectModel;
use App\Http\Model\SupplierModel;
use App\Http\Model\SupplierOrdersInfoModel;
use App\Http\Model\SupplierOrdersModel;
use App\Http\Model\SupplierOrdersReceivingInfoModel;
use App\Http\Model\SupplierOrdersReceivingModel;
use App\Http\Model\SupplierRepaymentModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class SupplierOrdersController extends Controller
{
    /**
     * 采购订单
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function orderLists(Request $request){
        $rules = [
            'projectId' => 'required|integer',
            'supplierId' => 'nullable|integer',
            'status' => 'nullable|integer|in:0,1,2',
            'length' => 'nullable|integer|in:10,20,50',
            'page' => 'nullable|integer|min:1',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'supplierId.required' => '获取供应商参数失败',
            'supplierId.integer' => '供应商参数类型错误',
            'status.integer' => '订单状态参数类型错误',
            'status.in' => '订单状态参数值不正确',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('projectId','supplierId','status','search','page','length');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $lists = $supplierOrdersModel->lists($param);
            $countLists = $supplierOrdersModel->countLists($param);
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 750101);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function deleteOrder(Request $request){
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取项目参数失败',
            'id.integer' => '项目参数类型错误',
        ];
        $param = $request->only('id');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $info = $supplierOrdersModel->info($param);
            if(empty($info)){
                throw new ApiException('记录不存在或已被删除，请刷新重试', 750601);
            }
            if ($info['status'] !=0){
                throw new ApiException('已经开始收货，不能删除这条记录', 750601);
            }
            $supplierOrdersModel->deleteOrder($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function orderInfo(Request $request){
        $rules = [
            'orderId' => 'required|integer',
        ];
        $message = [
            'orderId.required' => '获取采购单参数失败',
            'orderId.integer' => '采购单参数类型错误',
        ];
        $param = $request->only('orderId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $this->data = $supplierOrdersInfoModel->lists($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function orderInfo2(Request $request){
        $rules = [
            'orderId' => 'required|integer',
        ];
        $message = [
            'orderId.required' => '获取采购单参数失败',
            'orderId.integer' => '采购单参数类型错误',
        ];
        $param = $request->only('orderId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $supplierOrderModel = new SupplierOrdersModel();
            $order = DB::table('supplier_orders')
                ->leftJoin('supplier','supplier.id','supplier_orders.supplierId')
                ->where('supplier_orders.id',$param['orderId'])
                ->select('supplier_orders.*','supplier.name as supplierName')->first();
            $orderInfo = $supplierOrdersInfoModel->lists($param);
            $this->data = ['order'=>$order,'orderInfo'=>$orderInfo];
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function deleteOrderInfo(Request $request){
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取采购单参数失败',
            'id.integer' => '采购单参数类型错误',
        ];
        $param = $request->only('id');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $info = $supplierOrdersInfoModel->info($param);
            if ($info['status'] !=0){
                throw new ApiException('已收货或在收货中，不能删除', 750601);
            }
            $param['orderId'] =$info['orderId'];
            $supplierOrdersInfoModel->delete($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function receive(Request $request){
        $rules = [
            'orderId' => 'required|integer',
            'projectId' => 'required|integer',
            'receivedTime' => 'required|date_format:Y-m-d',
        ];
        $message = [
            'orderId.required' => '获取采购单参数失败',
            'orderId.integer' => '采购单参数类型错误',
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'receivedTime.required' => '请选择收货看日期',
            'receivedTime.date_format' => '收货日期格式不正确',
        ];
        $param = $request->only('orderId','data','projectId','receivedTime');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $rules1 = [
                'id' => 'required|integer',
                'received' => 'required|numeric',
            ];
            $message1 = [
                'id.required' => '获取参数失败',
                'id.integer' => '参数类型错误',
                'received.required' => '获取收货数量失败',
                'received.numeric' => '收货数量类型错误',
            ];
            $param['adminId'] = $request->session()->get('adminId');
            foreach ($param['data'] as $key => $a) {
                $validator1 = Validator::make($a, $rules1, $message1);
                if (!$validator1->passes()) {
                    throw new ApiException($validator->errors()->first(), 322502);
                }
            }

            $supplierOrdersModel = new SupplierOrdersModel();
            $supplierOrdersModel->receive($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * 项目完成收货确认
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function received(Request $request){
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取项目参数失败',
            'id.integer' => '项目参数类型错误',
        ];
        $param = $request->only('id');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $supplierOrdersModel->received($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function complete(Request $request){
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取项目参数失败',
            'id.integer' => '项目参数类型错误',
        ];
        $param = $request->only('id');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $supplierOrdersModel->complete($param);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function orderReceived(Request $request){
        $rules = [
            'orderId' => 'required|integer',
        ];
        $message = [
            'orderId.required' => '获取采购单参数失败',
            'orderId.integer' => '采购单参数类型错误',
        ];
        $param = $request->only('orderId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $supplierOrdersReceivingModel = new SupplierOrdersReceivingModel();
            $supplierOrdersReceivingInfoModel = new SupplierOrdersReceivingInfoModel();
            $orderInfo = $supplierOrdersInfoModel->lists($param);
            $receivingLists = $supplierOrdersReceivingModel->lists($param);
            foreach ($orderInfo as $o){
                $tmp[] = [
                    'amount'=>$o->amount,
                    'receivingTime' =>'',
                ];
                foreach ($receivingLists as $rl){
                    $i = $supplierOrdersReceivingInfoModel->info(['receivingId'=>$rl->id,'orderInfoId'=>$o->id]);
                    $tmp[] = [
                        'amount'=>isset($i['amount'])?$i['amount']:0,
                        'receivingTime' =>$rl->receivingTime,
                    ];
                }
                $this->data[] = [
                    'materialName'=>$o->materialName,
                    'spec'=>$o->spec,
                    'info' =>$tmp,
                ];
                unset($tmp);
            }
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * 供应商货款结算
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function supplierFinance(Request $request){
        $rules = [
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:1',
        ];
        $message = [
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('length','page','search');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierModel = new SupplierModel();
            $supplierOrdersModel = new SupplierOrdersModel();
            $lists = $supplierModel->lists($param);
            $countLists = $supplierModel->countLists($param);
            foreach ($lists as $k => $l) {
                $lists[$k]->orderSum = $supplierOrdersModel->getSum(['supplierId'=>$l->id]);
                $lists[$k]->unpaySum = $supplierOrdersModel->getSum(['supplierId'=>$l->id,'isPay'=>0]);
                $lists[$k]->paySum = $supplierOrdersModel->getSum(['supplierId'=>$l->id,'isPay'=>1]);
            }
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 710401);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function supplierProjectFinance(Request $request){
        $rules = [
            'supplierId' => 'required|integer',
            'length' => 'required|integer|in:10,20,50',
            'page' => 'required|integer|min:1',
        ];
        $message = [
            'supplierId.required' => '获取供应商参数失败',
            'supplierId.integer' => '供应商参数类型错误',
            'length.required' => '获取记录条数失败',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.required' => '获取起始记录位置失败',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('length','page','supplierId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $projectModel = new ProjectModel();
            $supplierId = $param['supplierId'];unset($param['supplierId']);
            $lists = $projectModel->lists($param);
            $countLists = $projectModel->countLists($param);
            foreach ($lists as $k => $l) {
                $lists[$k]->ordersSum = $supplierOrdersModel->getSum(['supplierId'=>$supplierId,'projectId'=>$l->id]);
                $lists[$k]->unpaySum = $supplierOrdersModel->getSum(['supplierId'=>$supplierId,'projectId'=>$l->id,'isPay'=>0]);
                $lists[$k]->paySum = $supplierOrdersModel->getSum(['supplierId'=>$supplierId,'projectId'=>$l->id,'isPay'=>1]);
            }
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 710501);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     * @throws \Exception
     */
    public function supplierProjectOrdersFinance(Request $request){
        $rules = [
            'supplierId' => 'required|integer',
            'projectId' => 'required|integer'
        ];
        $message = [
            'supplierId.required' => '获取供应商参数失败',
            'supplierId.integer' => '供应商参数类型错误',
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
        ];
        $param = $request->only('supplierId','projectId');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierModel = new SupplierModel();
            $supplierOrdersModel = new SupplierOrdersModel();
            $info = $supplierModel->info(['id'=>$param['supplierId']]);
            $param['startTime'] = $info['createTime'];
            $this->data = $supplierOrdersModel->accountsPerMonth($param);
        } else {
            throw new ApiException($validator->errors()->first(), 710601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function orderListsPerMonth(Request $request){
        $rules = [
            'supplierId' => 'required|integer',
            'projectId' => 'required|integer',
            'month' => 'required|date:Y-m'
        ];
        $message = [
            'supplierId.required' => '获取供应商参数失败',
            'supplierId.integer' => '供应商参数类型错误',
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'month.required' => '获取月份失败',
            'month.date' => '月份参数类型错误',
        ];
        $param = $request->only('supplierId','projectId','month');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersModel = new SupplierOrdersModel();
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $lists = $supplierOrdersModel->listPerMonth($param);
            foreach ($lists as $key => $list) {
                $infoLists = $supplierOrdersInfoModel->lists(['orderId'=>$list->id]);
                $lists[$key]->info = $infoLists;
            }
            $this->data = $lists;
        } else {
            throw new ApiException($validator->errors()->first(), 710801);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function repaymentLists(Request $request){
        $rules = [
            'supplierId' => 'required|integer',
            'projectId' => 'required|integer',
            'month' => 'nullable|date:Y-m',
            'length' => 'nullable|integer|in:10,20,50',
            'page' => 'nullable|integer|min:1',
        ];
        $message = [
            'supplierId.required' => '获取供应商参数失败',
            'projectId.integer' => '供应商参数类型错误',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('supplierId','projectId','month','length','page');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierRepaymentModel = new SupplierRepaymentModel();
            $lists= $supplierRepaymentModel->lists($param);
            $countLists = $supplierRepaymentModel->countLists($param);
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(), 710801);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function repayment(Request $request)
    {
        $rules = [
            'projectId' => 'required|integer',
            'supplierId' => 'required|integer',
            'orderIds' => 'required|array',
            'totalPrice' => 'required|numeric',
            'repayTime' => 'required|date_format:Y-m-d',
        ];
        $message = [
            'projectId.required' => '获取项目参数失败',
            'projectId.integer' => '项目参数类型错误',
            'supplierId.required' => '获取供应商参数失败',
            'supplierId.integer' => '供应商参数类型错误',
            'orderIds.required' => '获取订单参数失败',
            'orderIds.array' => '订单参数类型不正确',
            'totalPrice.required' => '请填写还款金额',
            'totalPrice.numeric' => '还款金额类型不正确',
            'repayTime.required' => '请选择还款时间',
            'repayTime.date_format' => '还款时间格式不正确',
        ];
        $param = $request->only(['projectId','supplierId','orderIds', 'totalPrice', 'repayTime', 'remark']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierRepaymentModel = new SupplierRepaymentModel();
            $supplierRepaymentModel->repayment($param);
        } else {
            throw new ApiException($validator->errors()->first(), 710901);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function changeAmount(Request $request){
        $rules = [
            'id' => 'required|integer',
            'receivedQuantity' => 'required|numeric',
        ];
        $message = [
            'id.required' => '获取项目参数失败',
            'id.integer' => '项目参数类型错误',
            'receivedQuantity.required' => '获取收货数量失败',
            'receivedQuantity.integer' => '收货数量参数类型错误',
        ];
        $param = $request->only('id','receivedQuantity');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $supplierOrdersInfoModel = new SupplierOrdersInfoModel();
            $supplierOrdersInfoModel->update(['id'=>$param['id']],['receivedQuantity'=>$param['receivedQuantity']]);
        } else {
            throw new ApiException($validator->errors()->first(), 750601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }
}